<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item
            :to="{ name: 'WorkflowList' }"
            class="breadcrumb_active_item"
            >流程管理</el-breadcrumb-item
          >
          <el-breadcrumb-item class="breadcrumb_active_item">
            {{ workflowTitle }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>节点管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <!-- 节点数据 -->
    <el-row>
      <div class="workflow_manager_content">
        <el-row>
          <el-col :span="20">
            <el-timeline>
              <el-timeline-item color="#1890ff" size="large">
                <el-card>
                  <span class="card_title">流程开始</span>
                </el-card>
              </el-timeline-item>

              <el-timeline-item
                v-for="item in workflowlistData"
                :key="item.id"
                color="#1890ff"
                size="large"
              >
                <el-card v-if="item.type == 1">
                  <div slot="header" class="clearfix">
                    <span class="card_title">{{ item.title }}</span>
                    <el-button
                      style="float: right"
                      size="mini"
                      type="danger"
                      v-if="userType == 0"
                      @click="deleteBtn(item)"
                      >删除</el-button
                    >
                    <el-button
                      style="float: right; margin-right: 10px"
                      size="mini"
                      type="primary"
                      v-if="userType == 0"
                      @click="editBtn(item)"
                      >编辑</el-button
                    >
                  </div>
                  <div
                    v-for="userItem in item.audit"
                    :key="userItem.audit_userid"
                    class="card_content_box"
                  >
                    <div class="card_content name_val">
                      审核人: {{ userItem.username }}
                    </div>
                    <div class="card_content">
                      <div class="card_content_title">分管部门:</div>
                      <el-tag
                        v-for="tagItem in userItem.department"
                        :key="tagItem.id"
                        style="margin-right: 10px"
                      >
                        {{ tagItem.department_name }}</el-tag
                      >
                    </div>
                  </div>
                </el-card>

                <el-card v-else
                  ><span class="card_title">{{ item.title }}</span></el-card
                >
              </el-timeline-item>

              <el-timeline-item color="#1890ff" size="large">
                <el-button
                  size="small"
                  type="primary"
                  @click="addBtn()"
                  v-if="userType == 0"
                  >添加节点</el-button
                >
              </el-timeline-item>
            </el-timeline>
          </el-col>
        </el-row>
      </div>
    </el-row>
    <!-- 添加弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="650px"
    >
      <el-form
        ref="dialogDetailForm"
        :model="detailFormData"
        :rules="detailFormRules"
      >
        <el-form-item label="节点名称" prop="node_name" label-width="90px">
          <el-input
            style="width: 170px"
            size="small"
            v-model="detailFormData.node_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="manager_list_box">
        <div
          class="manager_list_item"
          v-for="auditItem in detailFormData.audit"
          :key="auditItem.index"
        >
          <div class="manager_list_item_title username_val">审核人:</div>
          <div class="manager_list_item_title" style="width: 120px">
            {{ auditItem.username }}
          </div>
          <div class="manager_list_item_title" style="width: 90px">
            分管部门:
          </div>
          <div class="tag_box">
            <el-tag
              v-for="item in auditItem.department"
              :key="item.index"
              style="margin-right: 10px; margin-bottom: 10px"
              >{{ item.department_name }}</el-tag
            >
          </div>
          <div>
            <el-button
              @click="removeBtn(auditItem)"
              size="mini"
              style="margin-top: 2px"
              v-if="userType == 0"
              type="danger"
              >删除</el-button
            >
          </div>
        </div>
        <div
          v-if="detailFormData.audit.length == 0"
          class="manager_list_item_title none_val"
        >
          暂无审核人
        </div>
      </div>
      <el-divider></el-divider>
      <div
        class="manager_list_item_title"
        style="font-size: 16px; font-weight: bold"
      >
        添加审核人:
      </div>
      <el-form ref="addUserForm" :model="addUserData" :rules="addUserRules">
        <el-form-item label="审核人" prop="addUserId" label-width="90px">
          <el-select
            size="mini"
            v-model="addUserData.addUserId"
            filterable
            clearable
            remote
            placeholder="请输入名称或手机号"
            :remote-method="remoteMethod"
            :loading="selectLoading"
          >
            <el-option
              v-for="item in userListData"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="addDepartment" label-width="90px">
          <el-select
            size="mini"
            v-model="addUserData.addDepartment"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.department_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-bottom: 10px">
          <el-button
            size="mini"
            type="primary"
            @click="addUserFn()"
            v-if="userType == 0"
            style="margin-left: 90px"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          v-if="dialogBtnKey == 2 && userType == 0"
          @click="dialogDetailFormSubmit()"
          >保存</el-button
        >
        <el-button
          size="small"
          type="primary"
          v-if="dialogBtnKey == 1 && userType == 0"
          @click="dialogDetailFormSubmit()"
          >确认</el-button
        >
        <el-button size="small" @click="dialogclose()">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/workflow/workflowManager.css" scoped></style>

<script>
export default {
  name: "WorkflowManager",
  components: {},
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      loadingKey: false,
      loadingText: "",
      workflowId: "", // 流程id
      workflowTitle: "", // 流程名称
      workflowlistData: [],
      dialogTitle: "", // 弹窗标题
      dialogVisible: false, // 弹窗显示
      userListData: [], // 用户列表
      departmentList: [], // 部门列表
      dialogBtnKey: "", // 弹窗确认按钮控制; 1. 新增确认;2. 编辑确认
      detailFormData: {
        flow_id: "",
        node_id: "",
        node_name: "",
        audit: [],
      }, // 弹窗提交数据
      detailFormRules: {
        node_name: [
          { required: true, message: "请输入节点名称", trigger: "blur" },
          {
            min: 2,
            max: 12,
            message: "长度在 2 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
      addUserData: {
        addUserId: "",
        addDepartment: [],
      }, // 添加审核人
      addUserRules: {
        addUserId: [
          { required: true, message: "请选择审核人", trigger: "change" },
        ],
        addDepartment: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
      },
      selectLoading: false,
    };
  },
  created: function () {
    let query = this.$route.query;
    if (query.id != undefined && query.id != "") {
      this.workflowId = query.id;
    }
    this.getListDataFn();
    this.getUserListDataFn();
    this.getDepartmentListDataFn();
  },
  methods: {
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/flow/show";
      let data = {
        id: this.workflowId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.workflowTitle = response.flow.title;
            that.workflowlistData = response.flow_node;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },

    // 获取用户列表数据
    getUserListDataFn: function (query) {
      let that = this;
      let url = "/admin/adminusers/index";
      let data = {
        keywords: "",
      };
      if (query) {
        data = {
          keywords: query,
        };
      }
      this.axios
        .post(url, data)
        .then((response) => {
          that.selectLoading = false;
          if (response.code == 0) {
            that.userListData = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.selectLoading = false;
          console.log(error);
        });
    },

    // 成员选择搜索
    remoteMethod: function (query) {
      if (query !== "") {
        this.selectLoading = true;
        this.getUserListDataFn(query);
      } else {
        this.selectLoading = true;
        this.getUserListDataFn();
      }
    },

    // 获取部门列表数据
    getDepartmentListDataFn: function (query) {
      let that = this;
      let url = "/admin/department/index";
      let data = {};
      this.axios
        .post(url, data)
        .then((response) => {
          that.selectLoading = false;
          if (response.code == 0) {
            that.departmentList = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.selectLoading = false;
          console.log(error);
        });
    },
    // 添加节点
    addBtn: function () {
      let that = this;
      this.dialogTitle = "新增节点";
      this.dialogBtnKey = 1;
      this.detailFormData = {
        flow_id: "",
        node_id: "",
        node_name: "",
        audit: [],
      };
      this.addUserData = {
        addUserId: "",
        addDepartment: [],
      };
      that.dialogVisible = true;
      this.$nextTick(function () {
        that.$refs.dialogDetailForm.clearValidate();
        that.$refs.addUserForm.clearValidate();
      });
    },
    // 编辑节点
    editBtn: function (item) {
      let that = this;
      this.dialogTitle = "编辑节点";
      this.dialogBtnKey = 2;
      let editObj = JSON.parse(JSON.stringify(item));
      this.detailFormData = {
        flow_id: editObj.flow_id,
        node_id: editObj.id,
        node_name: editObj.title,
        audit: editObj.audit,
      };
      this.addUserData = {
        addUserId: "",
        addDepartment: [],
      };
      that.dialogVisible = true;
      this.$nextTick(function () {
        that.$refs.dialogDetailForm.clearValidate();
        that.$refs.addUserForm.clearValidate();
      });
    },
    // 添加审核人
    addUserFn: function () {
      let that = this;
      this.$refs.addUserForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          let index = that.detailFormData.audit.findIndex((item) => {
            return item.audit_userid == that.addUserData.addUserId;
          });

          if (index != -1) {
            that.$message.error("不可重复添加");
            return false;
          }

          let addObj = {
            audit_userid: that.addUserData.addUserId,
            username: "",
            department: [],
          };
          let add_username = "";
          that.userListData.forEach((item) => {
            if (item.id == that.addUserData.addUserId) {
              add_username = item.username;
            }
          });

          let add_department = [];
          that.addUserData.addDepartment.forEach((k) => {
            that.departmentList.forEach((i) => {
              if (i.id == k) {
                add_department.push(i);
              }
            });
          });

          addObj.username = add_username;
          addObj.department = add_department;

          that.detailFormData.audit.push(addObj);
          that.addUserData = {
            addUserId: "",
            addDepartment: [],
          };
          that.$nextTick(function () {
            that.$refs.addUserForm.clearValidate();
          });
        }
      });
    },
    // 移除审核人
    removeBtn: function (item) {
      let that = this;
      let id = item.audit_userid;
      let newList = [];
      that.detailFormData.audit.forEach((item) => {
        if (item.audit_userid != id) {
          newList.push(item);
        }
      });

      that.detailFormData.audit = newList;
    },
    // 弹窗提交按钮
    dialogDetailFormSubmit: function () {
      let that = this;
      let url = "/admin/flow/addNode";
      let data = {};
      if (this.dialogBtnKey == 2) {
        data = {
          node_id: this.detailFormData.node_id,
          flow_id: this.workflowId,
          node_name: this.detailFormData.node_name,
        };
      } else {
        data = {
          flow_id: this.workflowId,
          node_name: this.detailFormData.node_name,
        };
      }
      let submit_audit = [];
      this.detailFormData.audit.forEach((item) => {
        let obj = {
          audit_userid: item.audit_userid,
        };
        let list = [];
        item.department.forEach((k) => {
          list.push(k.id);
        });
        obj.department_ids = list.join(",");
        submit_audit.push(obj);
      });

      data.audit = submit_audit;

      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that
            .$confirm("确认提交?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
            .then(() => {
              that.loadingText = "处理中...";
              that.loadingKey = true;
              that.axios
                .post(url, data)
                .then((response) => {
                  that.loadingKey = false;
                  if (response.code == 0) {
                    if (that.dialogBtnKey == 2) {
                      that.$message.success("修改成功");
                    } else {
                      that.$message.success("添加成功");
                    }
                    that.dialogclose();
                    that.getListDataFn();
                  } else {
                    that.$message.error(response.msg);
                  }
                })
                .catch(function (error) {
                  that.loadingKey = false;
                  console.log(error);
                });
            })
            .catch(() => {});
        }
      });
    },
    // 关闭弹窗
    dialogclose: function () {
      this.dialogVisible = false;
      this.getListDataFn();
    },
    // 删除节点
    deleteBtn: function (item) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        let url = "/admin/flow/deleteNode";
        let data = {
          node_id: item.id,
        };
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
  },
};
</script>
